<template>
  <div class="unit-management-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>单位管理</span>
          <el-button type="primary" @click="openAddDialog">添加</el-button>
        </div>
      </template>

      <el-table :data="units" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="unit_name" label="单位名称" />
        <el-table-column prop="recordGroupNum" label="全宗号" />
        <el-table-column prop="fileType" label="档案门类">
          <template #default="scope">
            {{ formatFileType(scope.row.fileType) }}
          </template>
        </el-table-column>
        <el-table-column prop="retentionPeriod" label="保管期限">
          <template #default="scope">
            {{ formatRetentionPeriod(scope.row.retentionPeriod) }}
          </template>
        </el-table-column>
        <el-table-column prop="orgIssue" label="机构问题" >
          <template #default="scope">
            <!-- {{ formatOrgIssue(scope.row.orgIssue) }} -->
              {{ scope.row.orgIssue }}
          </template>
        </el-table-column>
        <el-table-column prop="caseFileCate" label="案卷类别" />
        <el-table-column prop="createdDt" label="新增时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updatedDt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedDt" label="修改时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updatedDt) }}
          </template>
        </el-table-column>
        <el-table-column prop="createUser" label="新增人" />
        <el-table-column prop="updateUser" label="修改人" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="单位名称" prop="unit_name">
            <el-input v-model="formData.unit_name" />
          </el-form-item>
          <el-form-item label="全宗号" prop="recordGroupNum">
            <el-input v-model="formData.recordGroupNum" />
          </el-form-item>
          <el-form-item label="档案门类" prop="fileType">
            <el-select v-model="formData.fileType" placeholder="请选择">
              <el-option label="照片" value="ZP" />
              <el-option label="录音" value="LY" />
              <el-option label="录像" value="LX" />
              <!-- 可扩展更多选项 -->
            </el-select>
          </el-form-item>
          <el-form-item label="保管期限" prop="retentionPeriod">
            <el-select v-model="formData.retentionPeriod" placeholder="请选择">
              <el-option label="定期10年" value="D10" />
              <el-option label="定期30年" value="D30" />
              <el-option label="永久" value="Y" />
            </el-select>
          </el-form-item>
          <el-form-item label="机构问题" prop="orgIssue">
            <!-- <el-select v-model="formData.orgIssue" placeholder="请选择">
              <el-option
                v-for="item in orgIssueData"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select> -->
            <el-input v-model="formData.orgIssue" />
          </el-form-item>
          <el-form-item label="案卷类别" prop="caseFileCate">
            <el-input v-model="formData.caseFileCate" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUnits, createUnit, updateUnit, deleteUnit } from '@/api/unitManagement'
import { useUserStore } from '@/stores/user' // 引入用户store
import { formatDateTime } from '@/utils/timeUtil'
import { getOrgIssueData } from '@/utils/fileUtil'
import { template } from 'lodash-es'

// 获取当前用户信息
const userStore = useUserStore()
const currentUser = ref(userStore.userInfo)

// 数据
const units = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加单位')
const formData = ref({
  id: null,
  unit_name: '',
  recordGroupNum: '',
  fileType: '',
  retentionPeriod: '',
  orgIssue: '',
  caseFileCate: '',
  createTime: '',
  updateTime: '',
  creator: '', // 自动填充
  modifier: '' // 自动填充
})

const orgIssueData = ref(getOrgIssueData())
console.log(orgIssueData)
const formRef = ref(null)

// 表单验证规则
const rules = {
  unit_name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  recordGroupNum: [{ required: true, message: '请输入全宗号', trigger: 'blur' }],
  fileType: [{ required: true, message: '请选择档案门类', trigger: 'change' }],
  retentionPeriod: [{ required: true, message: '请选择保管期限', trigger: 'change' }],
  orgIssue: [{ required: true, message: '请输入机构问题', trigger: 'blur' }],
  // caseFileCate: [{ required: true, message: '请输入案卷类别', trigger: 'blur' }],
}

// 定义映射关系
const fileTypeMap = {
  'ZP': '照片',
  'LY': '录音',
  'LX': '录像'
}

const retentionPeriodMap = {
  'D10': '定期10年',
  'D30': '定期30年',
  'Y': '永久'
}

const orgIssueMap = ref({})
orgIssueData.value.forEach(item => {
  orgIssueMap.value[item.value] = item.name
})

// 获取单位列表
const loadUnits = async () => {
  try {
    const res = await getUnits()
    units.value = res || []
  } catch (error) {
    ElMessage.error('加载单位失败：' + error.message)
  }
}

// 打开添加对话框
const openAddDialog = () => {
  dialogTitle.value = '添加单位'
  formData.value = {
    id: null,
    unit_name: '',
    recordGroupNum: '',
    fileType: '',
    retentionPeriod: '',
    orgIssue: '',
    caseFileCate: '',
    createUser: currentUser.value.username || '',
    updateUser: currentUser.value.username || ''
  }
  dialogVisible.value = true
  nextTick(() => {
    formRef.value.resetFields()
  })
}

// 打开编辑对话框
const openEditDialog = (row) => {
  dialogTitle.value = '编辑单位'
  // 重置表单验证
  nextTick(() => {
    formRef.value.resetFields()
    formData.value = { ...row }
    formData.value.updateTime = new Date().toISOString() // 更新时间自动更新
    formData.value.modifier = currentUser.value.username || '' // 修改人自动更新
  })
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    if (formData.value.id) {
      // 编辑
      formData.value.updateTime = new Date().toISOString()
      formData.value.modifier = currentUser.value.username || ''
      await updateUnit(formData.value)
      ElMessage.success('更新成功')
    } else {
      // 新增
      formData.value.createTime = new Date().toISOString()
      formData.value.creator = currentUser.value.username || ''
      formData.value.updateTime = new Date().toISOString()
      formData.value.modifier = currentUser.value.username || ''
      await createUnit(formData.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    loadUnits() // 刷新列表
  } catch (error) {
    ElMessage.error('提交失败：' + error.message)
  }
}

// 删除单位
const handleDelete = async (id) => {
  await ElMessageBox.confirm('确定要删除该单位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  try {
    await deleteUnit(id)
    ElMessage.success('删除成功')
    loadUnits()
  } catch (error) {
    ElMessage.error('删除失败：' + error.message)
  }
}

// 初始化
onMounted(() => {
  loadUnits()
})

// 添加过滤器函数
const formatFileType = (value) => {
  return fileTypeMap[value] || value
}

const formatRetentionPeriod = (value) => {
  return retentionPeriodMap[value] || value
}

const formatOrgIssue = (value) => {
  const orgIssueData = getOrgIssueData()
  const item = orgIssueData.find(item => item.value === value)
  console.log('item', value)
  return item ? item.name : value
}
</script>

<style scoped>
.unit-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>